package itsm.isperp.module.controller.configuration;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.QueryFilter;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilter;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.configuration.ConfCategoryProperty;
import itsm.isperp.module.entity.configuration.ConfCiRelationType;
import itsm.isperp.module.entity.configuration.ConfCiRelationUsePropety;
import itsm.isperp.module.entity.db.DbEntityField;
import itsm.isperp.module.service.configuration.ConfCategoryPropertyService;
import itsm.isperp.module.service.configuration.ConfCategoryService;
import itsm.isperp.module.service.configuration.ConfCiRelationTypeService;
import itsm.isperp.module.service.configuration.ConfCiRelationUsePropetyService;
import itsm.isperp.module.service.db.DbEntityFieldService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 控制器
 * 
 * @author lizx
 * @date 2014-09-22 09:48
 */
@Controller
@RequestMapping("configuration/ciRelationType")
public class ConfCiRelationTypeController extends
		BaseController<ConfCiRelationType> {

	@Autowired
	protected ConfCiRelationTypeService confCiRelationTypeService;
	@Autowired
	protected ConfCategoryPropertyService confCategoryPropertyService;
	@Autowired
	protected ConfCiRelationUsePropetyService confCiRelationUsePropetyService;

	@Autowired
	protected DbEntityFieldService dbEntityFieldService;

	@Override
	public ConfCiRelationTypeService getService() {
		return this.confCiRelationTypeService;
	}

	@Override
	public String getPageTitle() {
		return "配置关系类型";
	}

	@RequestMapping("save")
	@ResponseBody
	@Override
	public ResultMessage save(ConfCiRelationType model, HttpServletRequest req) {

		if (!this.confCiRelationTypeService.exists(model.getId())) {

			ConfCiRelationType f1 = this.getService().findByCategory(
					model.getFromCategoryId(), model.getToCategoryId());

			ConfCiRelationType f2 = this.getService().findByCategory(
					model.getToCategoryId(), model.getFromCategoryId());
			if (f1 != null && StringUtils.isNotEmpty(f1.getId())) {
				return ResultMessage.failure("已存在名称为：" + f1.getName());
			} else if (f2 != null && StringUtils.isNotEmpty(f2.getId())) {

				return ResultMessage.failure("已存在名称为：" + f2.getName());
			}
		}
		String name = model.getFromCategoryName() + "->"
				+ model.getToCategoryName();
		model.setName(name.replace("/", ""));

		this.getService().saveOrUpdate(model, req);

		return ResultMessage.newInstance(true, null, model.getId());
	}

	@Override
	@RequestMapping("edit")
	public ModelAndView edit(String id, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = new ModelAndView("configuration/ciRelationType/edit");
		mv.addObject("pageTitle", this.getPageTitle());
		ConfCiRelationType model = null;
		if (StringUtils.isEmpty(id)) {
			model = new ConfCiRelationType();
			model.setId(HibernateUUIDGenerator.generate());
		} else {
			model = this.getService().findOne(id);
		}
		mv.addObject("model", model);
		return mv;
	}

	@RequestMapping("delete")
	@ResponseBody
	@Override
	public ResultMessage delete(String id, HttpServletRequest req) {

		this.getService().delete(id);
		this.confCiRelationUsePropetyService.deleteByRelationTypeId(id);

		return ResultMessage.newInstance(true);
	}

	@RequestMapping("usePropertyEdit")
	public ModelAndView usePropertyEdit(String id, String relationTypeId,
			HttpServletRequest req) throws Exception {
		ModelAndView mv = new ModelAndView(
				"configuration/ciRelationType/usePropertyEdit");

		ConfCiRelationUsePropety model = null;
		List<ConfCategoryProperty> fromProperties = null;
		List<ConfCategoryProperty> toProperties = null;
		String rtId = relationTypeId;
		if (StringUtils.isEmpty(id)) {
			model = new ConfCiRelationUsePropety();
			model.setId(HibernateUUIDGenerator.generate());
			model.setRelationTypeId(relationTypeId);

			QueryFilter qf = new JqGridFilter();
			qf.addRule("relationTypeId", JqGridFilterRuleOp.eq, relationTypeId);

			model.setOrderNum(this.confCiRelationUsePropetyService
					.findAllCount(qf).intValue() + 1);

		} else {
			model = this.confCiRelationUsePropetyService.findOne(id);
			rtId = model.getRelationTypeId();
		}

		ConfCiRelationType rt = this.getService().findOne(rtId);
		fromProperties = this.confCategoryPropertyService.findProperty(rt
				.getFromCategoryId());
		toProperties = this.confCategoryPropertyService.findProperty(rt
				.getToCategoryId());

		List<DbEntityField> fields = dbEntityFieldService
				.findAllByTableName("conf_ci");

		for (DbEntityField f : fields) {
			ConfCategoryProperty p = new ConfCategoryProperty();
			p.setId("field-" + f.getColumnName());
			p.setName(f.getName());

			fromProperties.add(p);
		}

		mv.addObject("relationType", rt);
		mv.addObject("fromProperties", fromProperties);
		mv.addObject("toProperties", toProperties);
		mv.addObject("model", model);
		return mv;
	}

	@ResponseBody
	@RequestMapping("listRelationTypes")
	public List<ConfCiRelationType> listRelationTypes(String fromCategoryId,
			HttpServletRequest req) {

		return this.confCiRelationTypeService
				.findByFromCategoryId(fromCategoryId);
	}

	@ResponseBody
	@RequestMapping("listByCategory")
	public List<Map<String, Object>> listByCategory(String categoryId,
			JqGridRequest req) {
		ConfCategoryService confCategoryService = ContextHolder
				.getSpringBean("confCategoryService");
		String treenodePath = confCategoryService.findOne(categoryId)
				.getTreenodePath();
		String parentCategoryId = "";
		if (StringUtils.isNotEmpty(treenodePath)) {
			String[] strBuf = treenodePath.split("/");
			List<String> strBufVal = new ArrayList<String>();
			for (String str : strBuf) {
				str = str.trim();
				if (StringUtils.isNotEmpty(str)) {
					strBufVal.add(str);
				}
			}
			if (strBufVal.size() > 1) {
				parentCategoryId = strBufVal.get(strBufVal.size() - 2);
			}

			if (StringUtils.isEmpty(parentCategoryId)) {
				parentCategoryId = "";
			}
		} else {
			return null;
		}
		String categoryIdLike = treenodePath.trim() + "%";
		return confCiRelationTypeService.findAllByCategory(categoryIdLike,
				parentCategoryId);
	}
}
